//https://leetcode.cn/problems/binary-tree-right-side-view/
package codeRandomThoughts.Test199二叉树的右视图;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 右视图代表层序遍历,每层的最后一个节点
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        //层序遍历用队列实现
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> result = new ArrayList<>();
        if (root == null)
            return result;

        //记录每层节点个数
        int npl = 0; //number per level
        TreeNode node = root;
        queue.offer(node);
        while (!queue.isEmpty()) {
            npl = queue.size();
            while (npl > 0) {
                node = queue.poll();
                if (npl==1){
                    result.add(node.val);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                npl--;
            }
        }
        return result;

    }
}
